/**
 * Progetto PRAISED.
 * 03/feb/2011
 */
package it.uniroma3.engine.util;

import it.uniroma3.engine.model.Token;
import it.uniroma3.engine.model.Tokenizer;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * GreekLetterFormatter : This class is responsible for managing spelled out the words with Greek letters
 * 
 * @author Accosta Augusto
 * @author Lopez Elisabetta
 *
 */
public class GreekLetterFormatter {

	private Map<String, String> letter2spelledout;	// Map of correspondences
	
	/**
	 * no-args constructor 
	 */
	public GreekLetterFormatter() {
		this.letter2spelledout = Utils.spelledOutGreekLettersEncodedMap;
	}

	/**
	 * This method checks if the letter is a greek letter
	 * 
	 * @param letter
	 * @return the boolean value
	 */
	public boolean isGreekLetter(String letter) {
		return this.letter2spelledout.containsKey(letter);
	}
	
	/**
	 * This method extracts the greek letters contained in the input text
	 * 
	 * @param text
	 * @return the extracted letters - empty string otherwise
	 * @throws IOException
	 */
	public String findGreekLetters(String text) throws IOException {
		StringBuffer strb = new StringBuffer();
		
		for (int i = 0; i < text.length(); i++) {
			if(isGreekLetter(Character.toString(text.charAt(i)))) {
				strb.append(text.charAt(i));
			}
		}
		
		return strb.toString();
	} 
	
	
	/**
	 * This method sobstitutes the greek simbols with their spelled out value
	 * 
	 * @param text
	 * @return the new text
	 * @throws IOException
	 */
	public String substituteGreekSimbolsBySpelledOutLetters(String text) throws IOException {
		List<Token> tokenList = Tokenizer.getTokens(text);
		StringBuffer str = new StringBuffer();
		
		for (Token token : tokenList) {
			String greekLetters = findGreekLetters(token.getToken());
			String result = format(greekLetters);
			
			token.setToken(token.getToken().replace(greekLetters, result));
			
			str.append(token.getToken() + " ");	
		}
		return str.toString().substring(0, str.lastIndexOf(" "));
	}
	
	
	/**
	 * This method make the format of the greek letters in input
	 * 
	 * @param greekLetters
	 * @return the spelled out letters
	 */
	private String format(String greekLetters) {
		
		StringBuffer strb = new StringBuffer();
		
		for(int i=0; i < greekLetters.length(); i++)
			 // TODO ho aggiunto uno spazio per separare tutti gli eventuali spelled out delle lettere greche
			strb.append(" " + this.letter2spelledout.get(Character.toString(greekLetters.charAt(i))) + " ");
		
		return strb.toString();
	}
	
}
